<template>
  <div id="page" style="padding:20px">
    <h4>工艺名称:材料厂工艺</h4>
    <div style="display: flex;border:1px solid #999">
      <!-- 左侧可拖动元素 -->
      <div style="flex: 1; padding:10px;">
        <div class="drag-wrap">
          <div v-for="(item, index) in items" :key="index" class="draggable-item" draggable="true"
            @dragstart="handleDragStart(item)" @dragend="handleDragEnd">
            {{ item.text }}
          </div>
        </div>
      </div>

      <!-- 右侧画布 -->
      <div style="flex: 5; padding: 10px;">
        <div class="canvas" @drop="handleDrop" @dragover.prevent @click="handleClickCanvas" ref="canvas">
          <div v-for="(item, index) in canvasItems" :key="index" class="canvas-item" :class="{ start: item.isStart }"
            :data-index="item.id" :id="item.id" :style="{ position: 'relative' }">
            <div>
              <span>
                {{ item.text }}
              </span>

              <!-- 使用 div 元素创建连线 -->
              <div v-if="index != 0" :style="{
                width:'2px',
                height:'40px',
                background:'black',
                 position:'absolute',
                top: `-50%`,
                left: `50%`,
                transform: `translate(-50%, -50%)`,
  
               }">
                <span class="arrow"></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 保存按钮 -->
    <button @click="saveData">Save</button>
  </div>
</template>

<script>
import { translate } from 'element-plus';

export default {
  name: 'App',
  data() {
    return {
      items: [
        { id: 1, text: 'Item 1' },
        { id: 2, text: 'Item 2' },
        { id: 3, text: 'Item 3' },
        { id: 4, text: 'Item 4' },
        { id: 5, text: 'Item 5' }
      ],
      canvasItems: [],
      draggedItem: null,
      connectorTop: 0,
      connectorLeft: 0,
      connectorWidth: 0,
      connectorHeight: 0,
      connectorAngle: 0
    };
  },
  methods: {
    handleMouseMove(event) {
      if (!this.draggedItem) return;
      this.$nextTick(()=>{

        // 获取鼠标相对于画布的位置
        const canvasRect = this.$refs.canvas.getBoundingClientRect();
        const mouseX = event.clientX - canvasRect.left;
        const mouseY = event.clientY - canvasRect.top;
  
        // 检查鼠标位置是否在某个现有元素的上方
        let insertIndex = -1;
        for (let i = 0; i < this.canvasItems.length; i++) {
          const itemRect = this.$refs.canvas.querySelector(`[data-index="${i}"]`).getBoundingClientRect();
          if (mouseY >= itemRect.top && mouseY <= itemRect.bottom) {
            // 如果在元素顶部或底部附近，则允许在它们之间插入
            if (mouseY <= itemRect.top + 10 || mouseY >= itemRect.bottom - 10) {
              insertIndex = i;
              break;
            }
          }
        }
  
        // 标记插入位置
        this.insertIndex = insertIndex;
      })
    },
    handleDragStart(item) {
      this.draggedItem = item;
    },
    handleDragEnd() {
      this.draggedItem = null;
      
    },
    handleDrop(event) {
      if (this.draggedItem) {

        const canvasRect = this.$refs.canvas.getBoundingClientRect();
        const mouseX = event.clientX - canvasRect.left;
        const mouseY = event.clientY - canvasRect.top;

        let insertIndex = -1;
        for (let i = 0; i < this.canvasItems.length; i++) {
          const itemRect = this.$refs.canvas.querySelector(`[data-index="${i}"]`).getBoundingClientRect();
          if (mouseY >= itemRect.top - 10 && mouseY <= itemRect.bottom + 10) {
            // 假设在元素上方或下方10px内都视为间隙  
            if (i === 0 || mouseY <= itemRect.top) {
              // 插入到当前元素之前  
              insertIndex = i;
            } else {
              // 插入到当前元素之后  
              insertIndex = i + 1;
            }
            break;
          }
        }
        console.log(insertIndex,'insertIndex')



        const newItem = { ...this.draggedItem, isStart: false };
        this.canvasItems.push(newItem);

        // 如果是第一个元素，标记为开始元素
        if (this.canvasItems.length === 1) {
          this.canvasItems[0].isStart = true;
        }

        this.draggedItem = null;

        // 更新连线位置
      }
    },
    handleDrop2(event) {
      if (!this.draggedItem) return;

      const canvasRect = this.$refs.canvas.getBoundingClientRect();
      const mouseX = event.clientX - canvasRect.left;
      const mouseY = event.clientY - canvasRect.top;

      let insertIndex = -1;
      for (let i = 0; i < this.canvasItems.length; i++) {
        const itemRect = this.$refs.canvas.querySelector(`[data-index="${i}"]`).getBoundingClientRect();
        if (mouseY >= itemRect.top - 10 && mouseY <= itemRect.bottom + 10) {
          // 假设在元素上方或下方10px内都视为间隙  
          if (i === 0 || mouseY <= itemRect.top) {
            // 插入到当前元素之前  
            insertIndex = i;
          } else {
            // 插入到当前元素之后  
            insertIndex = i + 1;
          }
          break;
        }
      }

      if (insertIndex !== -1) {
        const newItem = { ...this.draggedItem, isStart: false };
        this.canvasItems.splice(insertIndex, 0, newItem);

        // 更新连线逻辑（假设您有这个方法）  
        // this.updateConnections();  

        // 重置 draggedItem  
        this.draggedItem = null;
      }  },
    handleClickCanvas() {
      if (this.canvasItems.length) {
        const lastItem = this.canvasItems[this.canvasItems.length - 1];
        console.log('Last Dragged Item:', lastItem);
      }
    },
    saveData() {
      localStorage.setItem('canvasItems', JSON.stringify(this.canvasItems));
    },

  },
  mounted() {
    const savedData = localStorage.getItem('canvasItems');
    if (savedData) {
      this.canvasItems = JSON.parse(savedData);

      // 重新计算连线位置
    }
  }
};
</script>

<style scoped>
.drag-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  border-right:1px solid #ccc
}
.draggable-item {
  cursor: move;
  padding: 10px;
  margin: 5px;
  background-color: lightblue;
  border-radius: 5px;
  width: 140px;
  height:40px;


}

.canvas {
  position: relative;
  /* border: 1px solid #ccc; */
  padding: 10px;
  min-height: 300px;
  text-align: center;
  display: flex;
  align-items: center;
  flex-direction: column;
}

.canvas-item {
  width: 200px;
  height: 60px;
  line-height: 60px;
  margin: 5px;
  background-color: lightgreen;
  border-radius: 5px;
  position: relative;
  margin-bottom: 50px;
  /* position: absolute; */
}

.start {
  background-color: lightcoral;
}

/* 连线样式 */
.connector {
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  background-color: black;
  transform-origin: left center;
}

/* 箭头样式 */
.arrow {
  content: '';
  position: absolute;
  right: -9px;
  top: 40px;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-top: 10px solid black;
}

</style>